<template>
  <div>
    <el-upload
      v-show="!isShowPro"
      class="avatar-uploader"
      action="#"
      :http-request="onRequest"
      list-type="picture-card"
      :file-list="fileList"
      :on-preview="onPreview"
      :on-remove="onRemove"
      :on-change="onChange"
      :before-upload="beforeupload"
      accept="image/png,image/gif"
      :limit="limit"
      :on-exceed="onExceed"
    >
      <!-- accept="image/png,image/gif" -->
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>

    <el-progress v-if="isShowPro" type="circle" :percentage="percentage" />
    <el-dialog
      title="头像"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <img :src="imgUrl" alt="">
    </el-dialog>
    <div slot="tip" class="el-upload__tip">只能上传gif/png文件，且不超过500kb</div>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDjIcgTzGH3YmjPpyrUqvkIZZJn1xc08zZ',
  SecretKey: 'MSIrACySfbHhqiKfjX5NO8cpkOnwoPko'
})
export default {
  props: {
    limit: {
      type: Number,
      default: () => 0
    }
  },
  data() {
    return {
      imageUrl: '',
      dialogVisible: false,
      fileList: [
        // { name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100' }
      ],
      imgUrl: '',
      percentage: 0,
      isShowPro: false
    }
  },

  created() {

  },

  methods: {
    onRequest(data) {
      this.isShowPro = true
      // 已选择图片 并上传到了本地
      this.id = setInterval(() => {
        if (this.percentage < 97) {
          this.percentage++
        } else {
          clearInterval(this.id)
          this.percentage = 95
        }
      }, 200)
      cos.putObject({
        Bucket: 'hrsaas-24-1308960769', /* 填入您自己的存储桶，必须字段 */
        Region: 'ap-shanghai', /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Key: data.file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        StorageClass: 'STANDARD',
        Body: data.file, // 上传文件对象
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          if (progressData.percent === 1) {
            this.percentage = 100
            clearInterval(this.id)

            setTimeout(() => {
              this.isShowPro = false
              this.percentage = 0
            }, 500)
          }
        }
      }, (err, data) => {
        // 如果上传失败
        if (err) {
          this.isShowPro = false
          this.$message.error('网络错误,上传失败')
          this.fileList.splice(this.fileList.length - 1, 1)
        }
        if (!err && data.statusCode === 200) {
          this.$message.success('图片上传成功')
          this.fileList[this.fileList.length - 1].url = 'https://' + data.Location
          this.$emit('on-success', this.fileList)
        }
      })
    },
    // 点击yulan
    onPreview(file) {
      this.imgUrl = file.url
      this.dialogVisible = true
    },
    // 点击删初
    onRemove(file, fileList) {
      this.fileList = fileList
    },
    // 上传之前
    beforeupload(file) {
      const imgType = ['image/png', 'image/gif']
      if (!imgType.includes(file.type)) {
        this.$message.error('请上传正确格式的图片')

        return false
      }
      const maxSize = 1 * 1024 * 1024
      if (file.size > maxSize) {
        this.$message.error('图片过大 不能超过1MB')
        return false
      }
    },
    // 文件发生变化上传成功或失败
    onChange(file, fileList) {
      this.fileList = fileList
    },
    // 超出文件最大上量
    onExceed() {
      this.$message.error('最多只能上传' + this.limit + '张图片')
    }
  }
}
</script>

<style  lang='scss'>
 .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
  }
  .disabled .el-upload--picture-card {
  display: none
}
</style>

